package gosnoopers.fr;

import java.util.ArrayList;
import java.util.HashMap;

import lazy_listview.JSONfunctions;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.Toast;

import common.Common;

public class InscriptionInfoActivity extends Activity {

	public static EditText police_org, address, local, town, zipcode, phone1,
			phone2, email, phone_snoop, firstname, lastname, unit, email_snoop,
			description;
	public ScrollView sview1;
	//****************************check Connect*************************
	public boolean isNetworkAvailable() {
		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo activeNetworkInfo = connectivityManager
				.getActiveNetworkInfo();
		return activeNetworkInfo != null && activeNetworkInfo.isConnected();
	}
	//******************************CREATE*****************************
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.inscription_info);
	
		police_org = (EditText) findViewById(R.id.police_org);
		address = (EditText) findViewById(R.id.address);
		local = (EditText) findViewById(R.id.local);
		town = (EditText) findViewById(R.id.town);
		zipcode = (EditText) findViewById(R.id.zipcode);
		phone1 = (EditText) findViewById(R.id.phone1);
		phone2 = (EditText) findViewById(R.id.phone2);
		email = (EditText) findViewById(R.id.email);
		phone_snoop = (EditText) findViewById(R.id.phone_snoop);
		firstname = (EditText) findViewById(R.id.firstname);
		lastname = (EditText) findViewById(R.id.lastname);
		unit = (EditText) findViewById(R.id.unit);
		email_snoop = (EditText) findViewById(R.id.email_snoop);
		description = (EditText) findViewById(R.id.description);

		sview1 = (ScrollView) findViewById(R.id.sview1);

		if (!isNetworkAvailable()) {
			CharSequence text = Common.MSG;
			Toast toast = Toast.makeText(getApplicationContext(), text,
					Toast.LENGTH_SHORT);
			toast.show();
		} else {
			new GetInfo().execute();
		}
		Button btn_save = (Button) findViewById(R.id.btn_save);
		btn_save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (validateEditText(police_org, "Police orgarisation empty!")
						&& validateEditText(address, "Adress empty!")
						&& validateEditText(local, "Local empty!")
						&& validateEditText(town, "Town empty!")
						&& validateEditText(zipcode, "Zipcode empty!")
						&& validateEditText(phone1, "Phone(1) empty!")
						&& validateEditText(phone2, "Phone(2) empty!")
						&& validateEditText(email, "Email empty!")
						&& validateEditText(phone_snoop, "Phone snoop empty!")
						&& validateEditText(firstname, "Firstname empty!")
						&& validateEditText(lastname, "Lastname empty!")
						&& validateEditText(unit, "Unit police number empty!")
						&& validateEditText(email_snoop, "Email snoop empty!")
						&& validateEditText(description, "Description empty!")) {
					if (!isNetworkAvailable()) {
						CharSequence text = Common.MSG;
						Toast toast = Toast.makeText(getApplicationContext(),
								text, Toast.LENGTH_SHORT);
						toast.show();
					} else {
						
						new DoSave().execute();
					}
				}
			}
		});

	}

	// **************************CHECK VALIDATE****************************
	public boolean validateEditText(EditText et, String msg) {
		et.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				v.setBackgroundResource(R.drawable.bg_border_editext);
				return false;
			}
		});

		if (et.getText().toString().matches("")) {

			et.requestFocus();
			et.setBackgroundResource(R.drawable.bg_border_editext_alert);
			Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT)
					.show();
			return false;
		} else
			return true;
	}

	// ****************************KEY DOWN******************************
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// Log.d("keyCode","sdsdf "+keyCode);
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			// your code
			// Log.d("BBBBBBBBBBBBBBBB",MainActivity.userId);
			if (MainActivity.userId.matches("0")) {

			} else {

				Intent goToNextActivity = new Intent(getApplicationContext(),
						Settings.class);
				startActivity(goToNextActivity);
			}
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	// ***************************************************************
	public static JSONObject jsonobject;
	public static JSONObject jsonobject2;
	boolean checkError = false;

	public static JSONArray jsonarray;
	ArrayList<HashMap<String, String>> arraylist;

	// ******************************GET INFO************************
	private class GetInfo extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {

			jsonobject = JSONfunctions
					.getJSONfromURL("http://gosnoopers.com/inscriptions/app/getInscription/author/"
							+ MainActivity.userId);
			// Log.i("DATA: =>",jsonobject.toString());
			try {

				jsonobject2 = jsonobject.getJSONObject("data");
				checkError = jsonobject.getBoolean("error");
				

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {

			if (!checkError) {
//				Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();

				// Log.i("DATA@@@@@@: =>",jsonobject2.toString());

				try {

					police_org.setText(jsonobject2.getString("police_org"));
					address.setText(jsonobject2.getString("address"));
					local.setText(jsonobject2.getString("local"));
					town.setText(jsonobject2.getString("town"));
					zipcode.setText(jsonobject2.getString("zipcode"));
					email.setText(jsonobject2.getString("email"));
					phone1.setText(jsonobject2.getString("phone1"));
					phone2.setText(jsonobject2.getString("phone2"));
					firstname.setText(jsonobject2.getString("firstname"));
					lastname.setText(jsonobject2.getString("lastname"));
					unit.setText(jsonobject2.getString("unit"));
					phone_snoop.setText(jsonobject2.getString("phone_snoop"));
					email_snoop.setText(jsonobject2.getString("email_snoop"));
					description.setText(jsonobject2.getString("description"));
					InscriptionAvatarActivity.logo = jsonobject2.getString("logo");

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			} else {

				Toast.makeText(getApplicationContext(), "Error!",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

	// ******************************SAVE**********************************
	private class DoSave extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {
			super.onPreExecute();
		}

		@Override
		protected Void doInBackground(Void... params) {

			// Retrieve JSON Objects from the given URL address

			String paramsURL = "police_org=" + police_org.getText().toString()
					+ "&address=" + address.getText().toString() + "&local="
					+ local.getText().toString() + "&town="
					+ town.getText().toString() + "&zipcode="
					+ zipcode.getText().toString() + "&email="
					+ email.getText().toString() + "&phone1="
					+ phone1.getText().toString() + "&phone2="
					+ phone2.getText().toString() + "&firstname="
					+ firstname.getText().toString() + "&lastname="
					+ lastname.getText().toString() + "&unit="
					+ unit.getText().toString() + "&phone_snoop="
					+ phone_snoop.getText().toString() + "&email_snoop="
					+ email_snoop.getText().toString() + "&description="
					+ description.getText().toString() + "&logo=" + null
					+ "&update=0" + "&author=" + MainActivity.userId;

			jsonobject = JSONfunctions.executeUrlWithOption(true,
					"http://gosnoopers.com/inscriptions/app/update/id/"
							+ MainActivity.userId, paramsURL, false);
			Log.d("inscription info", "=>: " + jsonobject);
			try {
				checkError = jsonobject.getBoolean("error");

			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void args) {

			if (!checkError) {
				Toast.makeText(getApplicationContext(), "Save ok!",
						Toast.LENGTH_SHORT).show();

			} else {

				Toast.makeText(getApplicationContext(), "Error!",
						Toast.LENGTH_SHORT).show();
			}
		}
	}

}
